/*
 * @Author: yangzonglong
 * @Date: 2021-03-10 15:38:29
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-07-20 14:52:31
 * @Auditor:
 */
import React, { forwardRef, useImperativeHandle, CSSProperties, useState, useEffect, useMemo, useRef } from 'react';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';
import { textReplaceStr } from '../../util';
import style from './text.module.scss';

const defStr = '请输入描述文字';

export interface TextProps extends CanvasItemProps {
  textProps?: {
    text?: string;
    textEn?: string;
    clearFormat?: boolean; // 为true时将清空格式，保留纯文本
  };
  style?: CSSProperties;
  scriptsChangeData?: object;
  children?: any;
}

interface RefProps {
  setData(html: string): void;
}

const App = (props: TextProps, ref: React.Ref<RefProps>) => {
  const { textProps, domComplete, scriptsChangeData, children, ...canvasProps } = props;
  const [value, setValue] = useState('');
  const [styles, setStyles] = useState<React.CSSProperties>({});
  const oText = useRef(''); // 记录原始的字符串模块，防止第二次后拿不到原始的

  useQueryControlWrap(canvasProps.id, '', domComplete);

  useEffect(() => {
    oText.current = (localStorage.i18nextLng === 'en' ? textProps?.textEn : textProps?.text) || '';
    setValue(oText.current);
  }, [textProps]);

  useImperativeHandle(ref, () => ({
    setData: (html: string | number | undefined) => {
      if(typeof html === 'string' || typeof html === 'number') {
        setValue(typeof html === 'number' ? html + '' : html)
      }else {
        if(oText.current && oText.current.includes('{{')) {
          setValue(textReplaceStr(oText.current, scriptsChangeData!))
        }
      }
    },
    setStyle: (styles: React.CSSProperties) => {
      setStyles(styles);
    }
  }));

  const combinestyle = useMemo(() => {
    return { ...props.style, ...styles };
  }, [styles, props.style]);
  
  let _value: string = value?.includes('{{') ? textReplaceStr(value, scriptsChangeData!) : (value || defStr);

  return !textProps?.clearFormat ? (
    <p
      dangerouslySetInnerHTML={{ __html: _value }}
      className={props.isDesign ? style.design : style.text}
      {...canvasProps}
      {...textProps}
      style={combinestyle}
    />
  ) : <div style={combinestyle} {...canvasProps}>{_value}</div>;
};

export default forwardRef(App);
